﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AnalyticsEngine.ClonesDetection;
using NClass.Core;
using NClass.DiagramEditor.ClassDiagram;
using NClass.DiagramEditor.ClassDiagram.Shapes;

namespace NClass.GUI.Dialogs
{
	public partial class CustomSearchDialog : Form
	{
		ClonesDetectionEngine m_searcher = null;
		Diagram m_currentDiagram = null;
		List<Shape> m_selectedShapes = null;
		DiagrammPartInfo m_example = null;

		public CustomSearchDialog()
		{
			InitializeComponent();
		}

		private void CustomSearchDialog_Load(object sender, EventArgs e)
		{
			m_okButton.Enabled = false;

			if (Workspace.Default.ActiveProject.ItemCount > 0)
			{
				List<Diagram> d = new List<Diagram>();
				foreach (IProjectItem pi in Workspace.Default.ActiveProject.Items)
				{
					if (pi is Diagram)
					{
						d.Add(pi as Diagram);
					}
				}
				m_currentDiagram = d[0];

				m_selectedShapes = m_currentDiagram.GetSelectedShapes().ToList<Shape>();

				List<TypeBase> sourceForPartInfo = new List<TypeBase>();
				foreach (Shape s in m_selectedShapes)
				{
					if (s.Entity is ClassType)
					{
						sourceForPartInfo.Add(s.Entity as ClassType);
					}
					else if (s.Entity is InterfaceType)
					{
						sourceForPartInfo.Add(s.Entity as InterfaceType);
					}
				}
				if (sourceForPartInfo.Count > 1)
				{
					m_example = new DiagrammPartInfo(sourceForPartInfo, m_currentDiagram);
					m_okButton.Enabled = m_example.IsCoupled;
				}

				m_selectedList.Items.Clear();
				foreach (TypeBase tb in sourceForPartInfo)
				{
					m_selectedList.Items.Add(tb.Name);
				}
			}
		}

		private void button1_Click(object sender, EventArgs e)
		{

		}

		private void button2_Click(object sender, EventArgs e)
		{
			Close();
		}
		SearchResults m_sr = null;
		private void m_okButton_Click(object sender, EventArgs e)
		{
			if (m_sr == null)
			{
				RunSearch();
			}
			else
			{
				DialogResult dr = MessageBox.Show("Are you really want to close your previous search results window", "Alert", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
				if (dr == System.Windows.Forms.DialogResult.Yes)
				{
					m_sr.Close();
					m_sr = null;
					RunSearch();
				}
			}
		}

		private void RunSearch()
		{
			m_searcher = new ClonesDetectionEngine(m_currentDiagram);
			m_searcher.AddExample(m_example);
			m_searcher.Search();

			m_sr = new SearchResults(m_searcher);
			m_sr.Show();
			m_sr.BringToFront();
			Hide();
		}

		private void m_selectedList_SelectedIndexChanged(object sender, EventArgs e)
		{

		}
	}
}
